package todo;

import done.AbstractWashingMachine;
import se.lth.cs.realtime.*;

public class TemperatureController extends PeriodicThread {
	private boolean ack;
	private int mode;
	private AbstractWashingMachine theMachine;
	private double temp;
	private TemperatureEvent e;
	private TemperatureEvent tmp;

	public TemperatureController(AbstractWashingMachine theMachine, long speed) {
		super(speed);
		this.theMachine = theMachine;
		ack = false;
		temp = 0;
		mode = TemperatureEvent.TEMP_IDLE;
	}

	public void perform() {
		tmp = (TemperatureEvent) mailbox.tryFetch();
		if (tmp != null) {
			e = tmp;
			temp = e.getTemperature();
			mode = e.getMode();
			ack = true;
		}

		if (mode == TemperatureEvent.TEMP_SET) {
			if (theMachine.getWaterLevel() > 0.0) {
				if (theMachine.getTemperature() > temp - 1.0) {
					theMachine.setHeating(false);

					if (ack) {
						ack = false;
						((WashingProgram) e.getSource()).putEvent(new AckEvent(
								this));
					}
				}
				if (theMachine.getTemperature() <= temp - 1.8) {
					theMachine.setHeating(true);

				}
			}
		} else if (mode == TemperatureEvent.TEMP_IDLE && ack) {
			theMachine.setHeating(false);
			ack = false;
		}

	}
}
